<?php

namespace app\common\model;
use think\Db;
use think\Model;

class Order extends Model {
    public $page_info;

    // 179 号文订单生成上传报文
    public function genPlatUploadData($order) {
        $order_info = $order['order_info'];

        $pay_request_data = json_decode($order['pay_info']['request_data'], true);
        $pay_response_data = json_decode($order['pay_info']['response_data'], true);
        $payExchangeInfoHead = [
            'guid' => $this->getGuidOnlyValue(),   // 系统唯一序号
            'initalRequest' => $pay_request_data['url'].'?'.$pay_request_data['params_str'],   // 原始请求
            'initalResponse' => json_encode($pay_response_data['post_str'], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES),   // 原始响应
//            'initalResponse' => 'ok',   // 原始响应
            'ebpCode' => config('customs_config.copCode'),   // 电商平台代码
            'payCode' => config('customs_config.payCode'),   // 支付企业代码
            'payTransactionId' => $order_info['trade_no'],   // 交易流水号
            'totalAmount' => $order_info['order_amount'] * 100,   // 交易金额
            'currency' => '142',   // 币制
            'verDept' => '3',   // 验核机构
            'payType' => $order_info['order_from'] == 1 ? '2' : '1',   // 支付类型
            'tradingTime' => date('YmdHis', $order_info['payment_time']),   // 交易成功时间
            'note' => '',   // 备注
        ];

        // 初始化支付配置
        // 通联微信支付
        $logic_payment = model('payment', 'logic');
        $result = $logic_payment->getPaymentInfo('allinpay');

        $paymentInfo = $result['data']['payment_config'];

        $goodsList = [];
        $goodsModel = new Goods();
        foreach($order_info['extend_order_goods'] as $key => $item) {
            $goods = $goodsModel->getGoodsInfo(['goods_id' => $item['goods_id']]);
            $goods_common = $goodsModel->getGoodsCommonInfoByID($goods['goods_commonid']);
            $goodsList[] = [
                'gname' => $goods_common['goods_name'],
                'itemLink'  => url('/home/goods/index',['goods_id' => $item['goods_id']], false, true),
            ];
        }

        $payExchangeInfoList = [
            [
                'orderNo'   => $order_info['order_sn'], // 交易平台向海关申报订单的的订单编号。需返回原始请求内的所有订单。
                'goodsInfo' => $goodsList, // 商品名称及商品展示链接地址列表
                'recpAccount'   => $paymentInfo['allinpay_mch_id'],    // 交易商品的卖方商户账号。电商平台自营商户应填写自营商户的收款账户；非自营电商应填写非自营商户的收款账户。
                'recpCode'      => config('customs_config.recpCode'),   // 应填写收款企业代码（境内企业为统一社会信用代码；境外企业可不填写）
                'recpName'      => config('customs_config.recpName'),   // 收款企业名称
            ]
        ];

        $payExInfoData = [
            'sessionID' => $order['session_id'],
            'payExchangeInfoHead' => $payExchangeInfoHead,
            'payExchangeInfoLists' => $payExchangeInfoList,
            'serviceTime'   => time() * 1000,
            'certNo'        => config('customs_config.uploadCerNo'),
        ];

        $platdataopen = Platdataopen::get($order['id']);
        $platdataopen->save([
            'upload_data' => json_encode($payExInfoData),
            'upload_state'  => PLATDATA_STATE_UNSIGNED,
        ]);
    }


    // 海关生成唯一guid值
    protected function getGuidOnlyValue(){
        $a4 = uniqid().rand(10,99);
        $a4 = $this->insertToStr($a4,4,'-');  //这里是后面两组的唯一值 如5770-A529AD987M
        $a4 = $a4.$this->GetRandStr(1);

        $a1 = $this->GetRandStr(5);
        $a2 = $this->GetRandStr(4);
        $a3 = $this->GetRandStr(4);
        $val = $a1.'-'.$a2.'-'.$a3.'-'.$a4;
        return strtoupper($val);
    }

    /**
     * 指定位置插入字符串
     * @param string $str  原字符串
     * @param int $i    插入位置
     * @param int $substr 插入字符串
     * @return string 处理后的字符串
     */
    protected function insertToStr($str, $i, $substr){
        $startstr="";
        for($j=0; $j<$i; $j++){
            $startstr .= $str[$j];
        }

        //指定插入位置后的字符串
        $laststr="";
        for ($j=$i; $j<strlen($str); $j++){
            $laststr .= $str[$j];
        }

        //将插入位置前，要插入的，插入位置后三个字符串拼接起来
        $str = $startstr . $substr . $laststr;

        //返回结果
        return $str;
    }

    /**
     * 获得指定位数随机数
     * @param int $length  指定位数
     * @return string  处理后的字符串
     */
    protected function GetRandStr($length){
        $str='ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
        $len=strlen($str)-1;
        $randstr='';
        for($i=0;$i<$length;$i++){
            $num=mt_rand(0,$len);
            $randstr .= $str[$num];
        }
        return $randstr;
    }

    /**
     * 取单条订单信息
     * @access public
     * @author yunku
     * @param array $condition 条件
     * @param array $extend 扩展 order_common,member,order_goods
     * @param string $fields 字段
     * @param array $order 排序
     * @param array $group 分组
     * @return array
     */
    public function getOrderInfo($condition = array(), $extend = array(), $fields = '*', $order = '', $group = '') {
        $order_info = db('order')->field($fields)->where($condition)->group($group)->order($order)->find();
        if (empty($order_info)) {
            return array();
        }
        if (isset($order_info['order_state'])) {
            $order_info['state_desc'] = get_order_state($order_info);
        }
        if (isset($order_info['payment_code'])) {
            $order_info['payment_name'] = get_order_payment_name($order_info['payment_code']);
        }

        //追加返回订单扩展表信息
        if (in_array('order_common', $extend)) {
            $order_info['extend_order_common'] = $this->getOrdercommonInfo(array('order_id' => $order_info['order_id']));
            $order_info['extend_order_common']['reciver_info'] = unserialize($order_info['extend_order_common']['reciver_info']);
            $order_info['extend_order_common']['invoice_info'] = unserialize($order_info['extend_order_common']['invoice_info']);
        }

        //返回买家信息
        if (in_array('member', $extend)) {
            $order_info['extend_member'] = model('member')->getMemberInfoByID($order_info['buyer_id']);
        }

        //追加返回商品信息
        if (in_array('order_goods', $extend)) {
            //取商品列表
            $order_goods_list = $this->getOrdergoodsList(array('order_id' => $order_info['order_id']));
            $order_info['extend_order_goods'] = $order_goods_list;
        }
        //dump($order_info);
        return $order_info;
    }

    /**
     * 获取订单信息
     * @access public
     * @author yunku
     * @param array $condition 条件
     * @param string $field 字段
     * @return array
     */
    public function getOrdercommonInfo($condition = array(), $field = '*') {
        return db('ordercommon')->where($condition)->find();
    }

    /**
     * 获取订单信息
     * @access public
     * @author yunku
     * @param array $condition 条件
     * @param bool $master 主服务器
     * @return type
     */
    public function getOrderpayInfo($condition = array(), $master = false) {
        return db('orderpay')->where($condition)->master($master)->find();
    }

    /**
     * 取得支付单列表
     * @access public
     * @author yunku
     * @param array $condition 条件
     * @param string $filed 字段
     * @param string $order 排序
     * @param string $key 以哪个字段作为下标,这里一般指pay_id
     * @return array
     */
    public function getOrderpayList($condition,  $filed = '*', $order = '', $key = '') {
        $pay_list = db('orderpay')->field($filed)->where($condition)->order($order)->select();
        if($key){
            $pay_list = sc_change_arraykey($pay_list, $key);
        }
        return $pay_list;
    }

    /**
     * 取得订单列表(未被删除)
     * @access public
     * @author yunku
     * @param unknown $condition 条件
     * @param string $page 分页
     * @param string $field 字段
     * @param string $order 排序
     * @param string $limit 限制
     * @param unknown $extend 追加返回那些表的信息,如array('order_common','order_goods')
     * @return Ambigous <multitype:boolean Ambigous <string, mixed> , unknown>
     */
    public function getNormalOrderList($condition, $page = '', $field = '*', $order = 'order_id desc', $limit = '', $extend = array()) {
        $condition['delete_state'] = 0;
        return $this->getOrderList($condition, $page, $field, $order, $limit, $extend);
    }

    /**
     * 取得订单列表(所有)
     * @access public
     * @author yunku
     * @param string|array $condition 条件
     * @param string $page 分页
     * @param string $field 字段
     * @param string $order 排序
     * @param string $limit 限制
     * @param array $extend 追加返回那些表的信息,如array('order_common','order_goods')
     * @param bool $master 主服务器
     * @return Ambigous <multitype:boolean Ambigous <string, mixed> , unknown>
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getOrderList($condition, $page = '', $field = '*', $order = 'order_id desc', $limit = '',$extend = array(), $master = false) {
        $list_paginate = db('order')->field($field)->where($condition)->order($order)->paginate($page, false, ['query' => request()->param()]);

        $this->page_info = $list_paginate;
        $list = $list_paginate->items();

        if (empty($list))
            return array();
        $order_list = array();
        foreach ($list as $order) {
            if (isset($order['order_state'])) {
                $order['state_desc'] = get_order_state($order);
            }
            if (isset($order['payment_code'])) {
                $order['payment_name'] = get_order_payment_name($order['payment_code']);
            }
            if (!empty($extend))
                $order_list[$order['order_id']] = $order;
        }
        if (empty($order_list))
            $order_list = $list;

        //追加返回订单扩展表信息
        if (in_array('order_common', $extend)) {
            $order_common_list = $this->getOrdercommonList(array('order_id' => array('in', array_keys($order_list))));
            foreach ($order_common_list as $value) {
                $order_list[$value['order_id']]['extend_order_common'] = $value;
                $order_list[$value['order_id']]['extend_order_common']['reciver_info'] = @unserialize($value['reciver_info']);
                $order_list[$value['order_id']]['extend_order_common']['invoice_info'] = @unserialize($value['invoice_info']);
            }
        }

        //追加返回买家信息
        if (in_array('member', $extend)) {
            foreach ($order_list as $order_id => $order) {
                $order_list[$order_id]['extend_member'] = model('member')->getMemberInfoByID($order['buyer_id']);
            }
        }

        $goods_model = new Goods();
        //追加返回商品信息
        if (in_array('order_goods', $extend)) {
            //取商品列表
            $order_goods_list = db('ordergoods')->where('order_id', 'in', array_keys($order_list))->select();

            if (!empty($order_goods_list)) {
                foreach ($order_goods_list as $value) {
                    $value['goods_info'] =  $goods_model->getGoodsInfo(['goods_id' => $value['goods_id']]);
                    $order_list[$value['order_id']]['extend_order_goods'][] = $value;
                }
            } else {
                $order_list[$value['order_id']]['extend_order_goods']= array();
            }
        }

        //追加返回拼团订单信息
        if (in_array('ppintuanorder', $extend)) {
            //取拼团订单附加列表
            $pintuanorder_list = model('ppintuanorder')->getPpintuanorderList(array('ppintuanorder.order_id' => array('in', array_keys($order_list))));
            if (!empty($pintuanorder_list)) {
                foreach ($pintuanorder_list as $value) {
                    $order_list[$value['order_id']]['pintuan_id'] = $value['pintuan_id'];
                    $order_list[$value['order_id']]['pintuangroup_id'] = $value['pintuangroup_id'];
                    $order_list[$value['order_id']]['pintuanorder_state'] = $value['pintuanorder_state'];
                    $order_list[$value['order_id']]['pintuanorder_state_text'] = $value['pintuanorder_state_text'];
                }
            }
        }

        return $order_list;
    }

    /**
     * 取得需要导出的订单
     * @access public
     * @author yunku
     * @param string|array $condition 条件
     * @param string $page 分页
     * @param string $field 字段
     * @param string $order 排序
     * @param string $limit 限制
     * @param array $extend 追加返回那些表的信息,如array('order_common','order_goods')
     * @param bool $master 主服务器
     * @return Ambigous <multitype:boolean Ambigous <string, mixed> , unknown>
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getOrderExcelList($condition, $page = '', $field = '*', $order = 'order_id desc', $limit = '',$extend = array(), $master = false) {

        $list_paginate = db('order a')->join('ordergoods b','a.order_id = b.order_id','left')->join('goods c','c.goods_id = b.goods_id')->where($condition)->order($order)->paginate($page, false, ['query' => request()->param()]);
        $this->page_info = $list_paginate;
        $list = $list_paginate->items();

        if (empty($list))
            return array();
        $order_list = array();
        foreach ($list as $order) {
            if (isset($order['order_state'])) {
                $order['state_desc'] = get_order_state($order);
            }
            if (isset($order['payment_code'])) {
                $order['payment_name'] = get_order_payment_name($order['payment_code']);
            }
            if (!empty($extend))
                $order_list[$order['order_id']] = $order;
        }
        if (empty($order_list))
            $order_list = $list;

        //追加返回订单扩展表信息
        if (in_array('order_common', $extend)) {
            $order_common_list = $this->getOrdercommonList(array('order_id' => array('in', array_keys($order_list))));
            foreach ($order_common_list as $value) {
                $order_list[$value['order_id']]['extend_order_common'] = $value;
                $order_list[$value['order_id']]['extend_order_common']['reciver_info'] = @unserialize($value['reciver_info']);
                $order_list[$value['order_id']]['extend_order_common']['invoice_info'] = @unserialize($value['invoice_info']);
            }
        }

        //追加返回买家信息
        if (in_array('member', $extend)) {
            foreach ($order_list as $order_id => $order) {
                $order_list[$order_id]['extend_member'] = model('member')->getMemberInfoByID($order['buyer_id']);
            }
        }


        //追加返回商品信息
        if (in_array('order_goods', $extend)) {
            //取商品列表
            $order_goods_list = db('ordergoods')->where('order_id', 'in', array_keys($order_list))->select();

            if (!empty($order_goods_list)) {
                foreach ($order_goods_list as $value) {

                    $order_list[$value['order_id']]['extend_order_goods'][] = $value;
                }
            } else {
                $order_list[$value['order_id']]['extend_order_goods']= array();
            }
        }

        //追加返回拼团订单信息
        if (in_array('ppintuanorder', $extend)) {
            //取拼团订单附加列表
            $pintuanorder_list = model('ppintuanorder')->getPpintuanorderList(array('ppintuanorder.order_id' => array('in', array_keys($order_list))));
            if (!empty($pintuanorder_list)) {
                foreach ($pintuanorder_list as $value) {
                    $order_list[$value['order_id']]['pintuan_id'] = $value['pintuan_id'];
                    $order_list[$value['order_id']]['pintuangroup_id'] = $value['pintuangroup_id'];
                    $order_list[$value['order_id']]['pintuanorder_state'] = $value['pintuanorder_state'];
                    $order_list[$value['order_id']]['pintuanorder_state_text'] = $value['pintuanorder_state_text'];
                }
            }
        }

        return $order_list;
    }

    /**
     * 取得(买/卖家)订单某个数量缓存
     * @access public
     * @author yunku
     * @param int $id   买家ID
     * @param string $key 允许传入  NewCount、PayCount、SendCount、EvalCount，分别取相应数量缓存，只许传入一个
     * @return array
     */
    public function getOrderCountCache($id, $key) {
        if (!config('cache_open')) return ;
        $types = $id.'_ordercount' . $key;
        $count = rkcache($types);
        return $count;
    }

    /**
     * 设置(买/卖家)订单某个数量缓存
     * @access public
     * @author yunku
     * @param int $id 买家ID
     * @param int $key 允许传入  NewCount、PayCount、SendCount、EvalCount、TradeCount，分别取相应数量缓存，只许传入一个
     * @param array $count 数据
     * @return type
     */
    public function editOrderCountCache($id, $key, $count) {
        if (!config('cache_open') || !intval($id))
            return;
        $types = $id.'_ordercount_' . $key;
        wkcache($types, $count);
    }

    /**
     * 取得买卖家订单数量某个缓存
     * @access public
     * @author yunku
     * @param int $id 买家ID
     * @param string $key 允许传入  NewCount、PayCount、SendCount、EvalCount，分别取相应数量缓存，只许传入一个
     * @return int
     */
    public function getOrderCountByID($id, $key) {
        $cache_info = $this->getOrderCountCache($id, $key);
        if (config('cache_open') && is_numeric($cache_info)) {
            //从缓存中取得
            $count = $cache_info;
        } else {
            //从数据库中取得
            $condition = array('buyer_id' => $id);
            $func = 'getOrderState' . $key;
            $count = $this->$func($condition);
            $this->editOrderCountCache($id, $key, $count);
        }
        return $count;
    }

    /**
     * 删除(买/卖家)订单全部数量缓存
     * @access public
     * @author yunku
     * @param string $type 买/卖家标志，允许传入 buyer
     * @param int $id   买家ID
     * @return bool
     */
    public function delOrderCountCache($type) {
        $type_NewCount = $type.'_ordercount' .'_NewCount';
        $type_PayCount = $type.'_ordercount' .'_PayCount';
        $type_SendCount = $type.'_ordercount' .'_SendCount';
        $type_EvalCount = $type.'_ordercount' .'_EvalCount';
        $type_TradeCount = $type.'_ordercount' .'_TradeCount';
        dcache($type_NewCount);
        dcache($type_PayCount);
        dcache($type_SendCount);
        dcache($type_EvalCount);
        dcache($type_TradeCount);
    }

    /**
     * 待付款订单数量
     * @access public
     * @author yunku
     * @param array $condition 条件
     * @return int
     */
    public function getOrderStateNewCount($condition = array()) {
        $condition['order_state'] = ORDER_STATE_NEW;
        return $this->getOrderCount($condition);
    }

    /**
     * 待发货订单数量
     * @access public
     * @author yunku
     * @param array $condition 条件
     * @return int
     */
    public function getOrderStatePayCount($condition = array()) {
        $condition['order_state'] = ORDER_STATE_PAY;
        return $this->getOrderCount($condition);
    }

    /**
     * 待收货订单数量
     * @access public
     * @author yunku
     * @param array $condition 条件
     * @return int
     */
    public function getOrderStateSendCount($condition = array()) {
        $condition['order_state'] = ORDER_STATE_SEND;
        return $this->getOrderCount($condition);
    }

    /**
     * 待评价订单数量
     * @access public
     * @author yunku
     * @param type $condition 检索条件
     * @return type
     */
    public function getOrderStateEvalCount($condition = array()) {
        $condition['order_state'] = ORDER_STATE_SUCCESS;
        $condition['evaluation_state'] = 0;
		$condition['refund_state'] = 0;
        return $this->getOrderCount($condition);
    }

    /**
     * 交易中的订单数量
     * @access public
     * @author yunku
     * @param array $condition 条件
     * @return int
     */
    public function getOrderStateTradeCount($condition = array()) {
        $condition['order_state'] = array(array('neq', ORDER_STATE_CANCEL), array('neq', ORDER_STATE_SUCCESS), 'and');
        return $this->getOrderCount($condition);
    }

    /**
     * 取得订单数量
     * @access public
     * @author yunku
     * @param array $condition 条件
     * @return int
     */
    public function getOrderCount($condition) {
        return db('order')->where($condition)->count();
    }

    /**
     * 取得订单商品表详细信息
     * @access public
     * @author yunku
     * @param array $condition 条件
     * @param string $fields 字段
     * @param string $order 排序
     * @return array
     */
    public function getOrdergoodsInfo($condition = array(), $fields = '*', $order = '') {
        return db('ordergoods')->where($condition)->field($fields)->order($order)->find();
    }

    /**
     * 取得订单商品表列表
     * @access public
     * @author yunku
     * @param type $condition 条件
     * @param type $fields 字段
     * @param type $limit 限制
     * @param type $page 分页
     * @param type $order 排序
     * @param type $group 分组
     * @param type $key 键
     * @return array
     */
    public function getOrdergoodsList($condition = array(), $fields = '*', $limit = null, $page = null, $order = 'rec_id desc', $group = null, $key = null) {
        if ($page) {
            $res= db('ordergoods')->field($fields)->where($condition)->order($order)->group($group)->paginate($page,false,['query' => request()->param()]);
            $this->page_info=$res;
            $ordergoods = $res->items();
            if(!empty($key)){
                $ordergoods = sc_change_arraykey($ordergoods, $key);
            }
            return $ordergoods;
        } else {
            $ordergoods = db('ordergoods')->field($fields)->where($condition)->limit($limit)->order($order)->group($group)->select();
            if(!empty($key)){
                $ordergoods = sc_change_arraykey($ordergoods, $key);
            }
            return $ordergoods;
        }
    }

    /**
     * 取得订单扩展表列表
     * @access public
     * @author yunku
     * @param array $condition 条件
     * @param string $fields 字段
     * @param string $order 排序
     * @param int $limit 限制
     * @return array
     */
    public function getOrdercommonList($condition = array(), $fields = '*', $order = '', $limit = null) {
        return db('ordercommon')->field($fields)->where($condition)->order($order)->limit($limit)->select();
    }

    /**
     * 插入订单支付表信息
     * @access public
     * @author yunku
     * @param array $data 参数内容
     * @return int 返回 insert_id
     */
    public function addOrderpay($data) {
        return db('orderpay')->insertGetId($data);
    }

    /**
     * 插入订单表信息
     * @access public
     * @author yunku
     * @param array $data 参数内容
     * @return int 返回 insert_id
     */
    public function addOrder($data) {
        $result = db('order')->insertGetId($data);
        if ($result) {
            //更新缓存
            \mall\queue\QueueClient::push('delOrderCountCache',array('buyer_id'=>$data['buyer_id']));
        }
        return $result;
    }

    /**
     * 插入订单扩展表信息
     * @access public
     * @author yunku
     * @param array $data 参数内容
     * @return int 返回 insert_id
     */
    public function addOrdercommon($data) {
        return db('ordercommon')->insertGetId($data);
    }

    /**
     * 插入订单扩展表信息
     * @access public
     * @author yunku
     * @param array $data 参数内容
     * @return int 返回 insert_id
     */
    public function addOrdergoods($data) {
        return db('ordergoods')->insertAll($data);
    }

    /**
     * 添加订单日志
     * @access public
     * @author yunku
     * @param type $data 数据信息
     * @return type
     */
    public function addOrderlog($data) {
        $data['log_role'] = str_replace(array('buyer', 'system', 'admin'), array('买家', '系统', '管理员'), $data['log_role']);
        $data['log_time'] = TIMESTAMP;
        return db('orderlog')->insertGetId($data);
    }

    /**
     * 更改订单信息
     * @access public
     * @author yunku
     * @param array $data 数据
     * @param array $condition 条件
     * @param int $limit 限制
     * @return bool
     */
    public function editOrder($data, $condition, $limit = '') {
        if(isset($data['order_state']) && isset($data['payment_time']) && $data['order_state'] == ORDER_STATE_PAY) {
            // 支付成功时，修改订单佣金结算状态
            $data['commission_state'] = COMMISSION_STATE_CALC;
        }

        $list = $this->getOrderList($condition);
        foreach ($list as $item) {
            if(!isset($data['order_state']) || $data['order_state'] == $item['order_state']) continue;
            if($data['order_state'] == ORDER_STATE_PAY) {   // 已支付
                Commission::orderCommissionStateChange($item, COMMISSION_STATE_CALC);
            } elseif ($data['order_state'] == ORDER_STATE_SUCCESS) {    // 订单收货后待结算
                Commission::orderCommissionStateChange($item, COMMISSION_STATE_ACTIVE);
            } elseif ($data['order_state'] == ORDER_STATE_CANCEL) {    // 取消订单标记失效
                Commission::orderCommissionStateChange($item, COMMISSION_STATE_INVALID);
            }
        }

        $update = db('order')->where($condition)->limit($limit)->update($data);
        if ($update) {
            //更新缓存
            \mall\queue\QueueClient::push('delOrderCountCache', $condition);
        }
        return $update;
    }

    /**
     * 更改订单信息
     * @access public
     * @author yunku
     * @param array $data 数据
     * @param array $condition 条件
     * @return bool
     */
    public function editOrdercommon($data, $condition) {
        return db('ordercommon')->where($condition)->update($data);
    }

    /**
     * 更改订单信息
     * @param array $data
     * @param array $condition
     * @return int|string
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function editOrdergoods($data, $condition) {
        return db('ordergoods')->where($condition)->update($data);
    }

    /**
     * 更改订单支付信息
     * @access public
     * @author yunku
     * @param type $data 数据
     * @param type $condition 条件
     * @return type
     */
    public function editOrderpay($data, $condition) {
        return db('orderpay')->where($condition)->update($data);
    }

    /**
     * 订单操作历史列表
     * @access public
     * @author yunku
     * @param type $condition 条件
     * @return Ambigous <multitype:, unknown>
     */
    public function getOrderlogList($condition) {
        return db('orderlog')->where($condition)->select();
    }

    /**
     * 取得单条订单操作记录
     * @access public
     * @author yunku
     * @param array $condition 条件
     * @param string $order 排序
     * @return array
     */
    public function getOrderlogInfo($condition = array(), $order = '') {
        return db('orderlog')->where($condition)->order($order)->find();
    }

    /**
     * 返回是否允许某些操作
     * @access public
     * @author yunku
     * @param type $operate 操作
     * @param type $order_info 订单信息
     * @return boolean
     */
    public function getOrderOperateState($operate, $order_info) {
        if (!is_array($order_info) || empty($order_info))
            return false;
        $state = '';
        switch ($operate) {

            //买家取消订单
            case 'buyer_cancel':
                $state = ($order_info['order_state'] == ORDER_STATE_NEW) ||
                        ($order_info['payment_code'] == 'offline' && $order_info['order_state'] == ORDER_STATE_PAY);
                break;

            //申请退款
            case 'refund_cancel':
                if (isset($order_info['refund'])) {
                    $state = $order_info['refund'] == 1 && !intval($order_info['lock_state']);
                } else {
                    $state = FALSE;
                }
                break;


            //平台取消订单
            case 'system_cancel':
                $state = ($order_info['order_state'] == ORDER_STATE_NEW) ||
                        ($order_info['payment_code'] == 'offline' && $order_info['order_state'] == ORDER_STATE_PAY);
                break;

            //平台收款
            case 'system_receive_pay':
                $state = $order_info['order_state'] == ORDER_STATE_NEW && $order_info['payment_code'] == 'online';
                break;

            case 'payment':
                $state = $order_info['order_state'] == ORDER_STATE_NEW && $order_info['payment_code'] == 'online';
                break;

            //调整运费
            case 'modify_price':
                $state = ($order_info['order_state'] == ORDER_STATE_NEW) || ($order_info['payment_code'] == 'offline' && $order_info['order_state'] == ORDER_STATE_PAY);
                $state = floatval($order_info['shipping_fee']) > 0 && $state;
                break;
            //调整商品价格
            case 'spay_price':
                $state = ($order_info['order_state'] == ORDER_STATE_NEW) ||
                        ($order_info['payment_code'] == 'offline' && $order_info['order_state'] == ORDER_STATE_PAY);
                $state = floatval($order_info['goods_amount']) > 0 && $state;
                break;

            //发货
            case 'send':
                $state = !$order_info['lock_state'] && $order_info['order_state'] == ORDER_STATE_PAY;
                break;

            //收货
            case 'receive':
                $state = !$order_info['lock_state'] && $order_info['order_state'] == ORDER_STATE_SEND;
                break;

            //评价
            case 'evaluation':
                $state = !$order_info['lock_state'] && !$order_info['evaluation_state'] && $order_info['order_state'] == ORDER_STATE_SUCCESS;
                break;

            //锁定
            case 'lock':
                $state = intval($order_info['lock_state']) ? true : false;
                break;

            //快递跟踪
            case 'deliver':
                $state = !empty($order_info['shipping_code']) && in_array($order_info['order_state'], array(ORDER_STATE_SEND, ORDER_STATE_SUCCESS));
                break;

            //放入回收站
            case 'delete':
                $state = in_array($order_info['order_state'], array(ORDER_STATE_CANCEL, ORDER_STATE_SUCCESS)) && $order_info['delete_state'] == 0;
                break;

            //永久删除、从回收站还原
            case 'drop':
            case 'restore':
                $state = in_array($order_info['order_state'], array(ORDER_STATE_CANCEL, ORDER_STATE_SUCCESS)) && $order_info['delete_state'] == 1;
                break;

            //分享
            case 'share':
                $state = true;
                break;
        }
        return $state;
    }

    /**
     * 联查订单表订单商品表
     * @access public
     * @author yunku
     * @param array $condition 条件
     * @param string $field 站点
     * @param number $page 分页
     * @param string $order 排序
     * @return array
     */
    public function getOrderAndOrderGoodsList($condition, $field = '*', $page = 0, $order = 'rec_id desc') {
        if($page){
            $list = db('ordergoods')->alias('order_goods')->where($condition)->field($field)->join('__ORDER__ order','order_goods.order_id=order.order_id','LEFT')->paginate($page,false,['query' => request()->param()]);
            $this->page_info = $list;
            return $list->items();
        }else{
            $list = db('ordergoods')->alias('order_goods')->where($condition)->field($field)->join('__ORDER__ order','order_goods.order_id=order.order_id','LEFT')->select();
            return $list;
        }
    }

    /**
     * 订单销售记录 订单状态为20、30、40时
     * @access public
     * @author yunku
     * @param unknown $condition  条件
     * @param string $field 字段
     * @param number $page 分页
     * @param string $order 排序
     * @return array
     */
    public function getOrderAndOrderGoodsSalesRecordList($condition, $field = "*", $page = 0, $order = 'rec_id desc') {
        $condition['order_state'] = array('in', array(ORDER_STATE_PAY, ORDER_STATE_SEND, ORDER_STATE_SUCCESS));
        return $this->getOrderAndOrderGoodsList($condition, $field, $page, $order);
    }

}
